class_name Player extends CharacterBody2D

var device: String = ""  #设备KEY  key  |  joy0_  joy1_  joy2_
var charactor_id: int = -1 #角色ID
const MAX_VELOCITY_DOWN := 800

@export var max_health := 1
@export var health := 0:
	set(v):
		health = v
		if health <= 0:
			Game.player_die(self)

@export var init_speed = 300
@export var speed = 300
@export var jump_speed = -450
@export var point = 0
@onready var line_2d: Line2D = $Line2D

@onready var graphics: Node2D = $Graphics

@onready var state_machine: StateMachine = $StateMachine
@onready var jump_timer: Timer = $JumpTimer

@onready var animation_player: AnimationPlayer = $AnimationPlayer


enum State{
	IDLE,
	FLY,
}

var default_gravity: float = ProjectSettings.get("physics/2d/default_gravity")


func reset() -> void:
	health = max_health
	point = 0


func move(delta: float) -> void:
	if health <= 0 || not Game.is_gaming():
		return
	
	velocity.x = speed
	if not is_on_floor():
		velocity.y += default_gravity * delta
		velocity.y = clamp(velocity.y, -MAX_VELOCITY_DOWN, MAX_VELOCITY_DOWN)
	var is_col := move_and_slide()
	if is_col:
		health -= 1


func transition_state(_from: int, to: int) -> void:
	#print("[%s] %s => %s" % [
		#Engine.get_physics_frames(),
		#State.keys()[from] if from != -1 else "<START>",
		#State.keys()[to],
	#])
	match to:
		State.IDLE:
			animation_player.play("idle")
		State.FLY:
			jump_timer.stop()
			animation_player.stop()
			animation_player.play("fly")
			SoundManager.play_sfx("BirdFly")
			velocity.y = jump_speed




func get_next_state(current_state: int) -> int:
	if jump_timer.time_left > 0:
		return State.FLY
	
	match current_state:
		State.FLY:
			if not animation_player.is_playing():
				return State.IDLE
	
	return StateMachine.KEEP_CURRENT

func tick_physics(state: int, delta: float) -> void:
	speed = init_speed + point
	match state:
		State.IDLE:
			move(delta)
		State.FLY:
			move(delta)



func _on_visible_on_screen_notifier_2d_screen_exited() -> void:
	if global_position.y >= (-get_canvas_transform().origin.y + get_viewport_rect().size.y): printt("下面")
	if global_position.y <= (-get_canvas_transform().origin.y): printt("上面")
	health -= 1


func get_award(data: Dictionary):
	point += data.point
	SoundManager.play_sfx("Coin")


